/**
 * 
 */
package com.tw.trips.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

/**
 * @author m1005264
 */
public class HTTPRequestPoster {
	/**
	 * Sends an HTTP GET request to a url
	 * 
	 * @param endpoint
	 *            - The URL of the server. (Example:
	 *            " http://www.yahoo.com/search")
	 * @param requestParameters
	 *            - all the request parameters (Example:
	 *            "param1=val1&param2=val2"). Note: This method will add the
	 *            question mark (?) to the request - DO NOT add it yourself
	 * @return - The response from the end point
	 */
	public static String sendGetRequest(String endpoint,
			String requestParameters) {
		String result = null;
		if (endpoint.startsWith("http://")) {
			// Send a GET request to the servlet
			try {
				System.setProperty("http.proxyHost", "internetmcc");
				System.setProperty("http.proxyPort", "8085");
				// Send data
				String urlStr = endpoint;
				if (requestParameters != null && requestParameters.length() > 0) {
					urlStr += "?" + requestParameters;
				}
				URL url = new URL(urlStr);
				URLConnection conn = url.openConnection();
				conn.setRequestProperty("content-type", "application/text");
				conn.setDoInput(true);
				conn.setDoOutput(true);
				// Get the response
				BufferedReader rd = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
				StringBuffer sb = new StringBuffer();
				String line;
				while ((line = rd.readLine()) != null) {
					sb.append(line);
				}
				rd.close();
				result = sb.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static void main(String[] args) {
		String ircts = sendGetRequest(
				"http://www.trainenquiry.com/RunningIslTrSt.aspx",
				"tr=12676&st=KPD+&dt=12%2f01%2f2012");
		String formatted = ircts.toUpperCase();
		formatted = formatted.replace("<B>", "");
		formatted = formatted.replace("</B>", "");
		Document doc = Jsoup.parse(formatted);
		Element data = doc.getElementById("TABLE3");
		System.out.println(data);
		XMLUtil util = new XMLUtil(data.toString());
		System.out.println(util.getTextFromAllTags("td"));
//		System.out.println(formatted.trim());
	}
}
